package Network

import (
	"SQL/myDB"
	"database/sql"
	"time"
)

//创建群：
//s nickname string,iconURL string,custom dictionary
//r Message string,
//  groupID

func createGroup(userID string, data dy_judge) (code int, msg string, result interface{}) {
	code, msg = canCreateGroup(userID)
	if code != Success {
		return
	}
	code, msg, nickname := data.judgeNickname("nickname")
	if code != Success {
		return
	}
	delete(data, "nickname")
	iconURL := defaultIconURL
	code, msg, custom := data.judgeCustom("group")
	if code != Success {
		return
	}

	return dealCreateGroup(nickname, iconURL, custom, userID)
}
func dealCreateGroup(nickname string, iconURL string, custom interface{}, owner string) (code int, msg string, result interface{}) {
	db := openDB()
	defer closeDB(db)

	tx, err := db.Begin()
	if err != nil {
		code = errBeginTx
		msg = err.Error()
		return
	}

	defer func() {
		if code != Success {
			err := tx.Rollback()
			if err != nil {
				code = errEndTx
				msg = err.Error()
			}
		}
	}()

	code, msg, groupID := insertIntoObjects(tx, nickname, iconURL, custom, false)
	if code != Success {
		return
	}

	err = myDB.TxExecSql(tx, "insert into groups(id,owner,createTime) values($1,$2,$3)", groupID, owner, time.Now())
	if err != nil {
		return errDBExecFailed, err.Error(), nil
	}

	err = myDB.TxExecSql(tx, "insert into members(groupID,userID,isManager) values($1,$2,true)", groupID, owner)
	if err != nil {
		return errDBExecFailed, err.Error(), nil
	}

	err = tx.Commit()
	if err != nil {
		return errEndTx, err.Error(), nil
	}
	return Success, "", map[string]string{"GroupID": groupID}
}

func insertIntoObjects(tx *sql.Tx, nickname string, iconURL string, custom interface{}, isUser bool) (code int, msg string, ID string) {
	stmt, rows, err := myDB.TxQuerySql(tx, `
	insert into objects(nickname,iconURL,custom,isUser)
	values ($1,$2,$3,$4) returning id
	`, nickname, iconURL, custom, isUser)
	defer stmt.Close()
	defer rows.Close()
	if err != nil {
		code = errDBQueryFailed
		msg = err.Error()
		return
	}

	if !rows.Next() {
		code = errDBQueryFailed
		msg = "no rows"
		return
	}

	err = rows.Scan(&ID)
	if err != nil {
		code = errRowsScan
		msg = err.Error()
		return
	}
	code = Success
	msg = ""
	return
}
